package org.edu.modules.scheduleCommon.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.edu.modules.scheduleCommon.entity.SysDict;
import org.edu.modules.scheduleCommon.mapper.SysDictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 1. 定义缓存服务

public class DictCacheService {

    @Autowired
    private SysDictMapper sysDictMapper;

    private RedisTemplate<String, Object> redisTemplate;

    public DictCacheService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostConstruct
    public void initDictCache() {
        LambdaQueryWrapper<SysDict> queryWrapper = new LambdaQueryWrapper<>();
        List<SysDict> dictList = sysDictMapper.selectList(queryWrapper);
        Map<String, Map<String, String>> dictMap = new HashMap<>();
        dictList.forEach(dict -> {
            dictMap.computeIfAbsent(String.valueOf(dict.getType()), k -> new HashMap<>())
                    .put(dict.getDictCode(), dict.getDictName());
        });
        redisTemplate.opsForValue().set("dictCache", dictMap);
    }

    public String getDictName(String type, String code) {
        Map<String, Map<String, String>> dictMap = (Map<String, Map<String, String>>) redisTemplate.opsForValue().get("dictCache");
        return dictMap != null && dictMap.get(type) != null
                ? dictMap.get(type).getOrDefault(code, code)
                : code;
    }
}
